package recall;

import java.util.ArrayList;
import java.util.List;

//子集
public class leetcode78 {
    public static void main(String[] args) {
        int[] nums = {1,2,3};
        List<List<Integer>> result = subsets2(nums);
        for (int i = 0; i < result.size(); i++) {
            System.out.println(result.get(i));
        }
    }

    public static List<List<Integer>> subsets(int[] nums){
        List<List<Integer>> results = new ArrayList<>();
        int n = 0; // 记录子集的内部个数；
        while(n <= nums.length){
            search(nums, n, 0, new ArrayList<>(), results);
            n++;
        }
        return results;
    }

    public static void search(int[] nums, int n, int start, List<Integer> path, List<List<Integer>> results){
        if(path.size() == n){
            results.add(new ArrayList<>(path));
            return;
        }
        for(int i = start; i < nums.length; i++){
            path.add(nums[i]);
            search(nums, n, i+1, path, results);
            path.removeLast();
        }
    }

    public static List<List<Integer>> subsets2(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(nums, 0, new ArrayList<>(), result);
        return result;
    }

    private static void backtrack(int[] nums, int start, List<Integer> current, List<List<Integer>> result) {
        result.add(new ArrayList<>(current)); // 添加当前子集到结果

        for (int i = start; i < nums.length; i++) {
            current.add(nums[i]); // 包含当前数字
            backtrack(nums, i + 1, current, result); // 递归处理下一个数字
            current.remove(current.size() - 1); // 回溯，不包含当前数字
        }
    }
}
